﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.JSON;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;

namespace WSDZ.KM.ZH.PurchaseOrderCollectEntry2
{
    [Description("采购订单保存汇总明细信息"), HotUpdate]
    public class PurchaseOrderCollectEntry : AbstractOperationServicePlugIn
    {
        public string logType { get; set; } = "采购订单保存汇总明细信息";
        public string btype { get; set; } = "采购订单保存汇总明细信息";
        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            base.AfterExecuteOperationTransaction(e);
            List<int> IdList = e.DataEntitys.Select(x => x["Id"].ToStringV1().ToInt32V1()).Distinct().Where(y => y != 0).ToList();
            if (IdList == null || IdList.Count < 1)
                return;
            Main(IdList);
        }
        public void Main(List<int> IdList)
        {
            List<PurData> dataList = new List<PurData>();
            int size = 5000;
            int icount = IdList.Count <= size ? 1 : IdList.Count % size > 0 ? IdList.Count / size + 1 : IdList.Count / size;
            for (int i = 0; i < icount; i++)
            {
                List<int> ids = IdList.Skip(i * size).Take(size).ToList();
                string sql = $@"select 
Id=main.FID
,billNo=main.FBILLNO
,entyId=enty.FENTRYID
,unitId=enty.FUNITID --采购单位Id
,priceUnitId=entyF.FPRICEUNITID --计价单位Id
,matId=mat.FMATERIALID --物料ID
,matNumber=mat.FNUMBER
,price=entyF.FPRICE
,isFree=enty.FGIVEAWAY --是否赠品
,taxPrice=entyF.FTAXPRICE --含税单价
,taxRate=entyF.FTAXRATE --税率
,discountRate=entyF.FDISCOUNTRATE --折扣率
,qty=enty.FQTY --采购数量
,allAmount=entyF.FALLAMOUNT  --价税合计
,amount=entyF.FAMOUNT --金额
,taxAmount=entyF.FTAXAMOUNT --税额
,discountAmount=entyF.FDISCOUNT --折扣额
from t_PUR_POOrderEntry enty
inner join T_PUR_POORDERENTRY_F entyF on enty.FENTRYID=entyF.FENTRYID
inner join t_PUR_POOrder main on enty.FID=main.FID
left join T_BD_MATERIAL mat on enty.FMATERIALID=mat.FMATERIALID
where main.FID in ({string.Join(",", ids)})
";
              

                DynamicObjectCollection datas = DBUtils.ExecuteDynamicObject(Context, sql);
                List<PurData> pList = datas.DynamicObjectCollectionToDataList<PurData>();
                dataList.AddRange(pList);
            }
            if (dataList.Count < 1)
                return;
            var dataDic = dataList.GroupBy(x => x.billNo).ToDictionary(y => y.Key, y => y.ToList());
            K3HelperV1.Login(Context);
            foreach (var dic in dataDic)
            {
                PurData firstData = dic.Value.FirstOrDefault();
                //List<int> entyids = dic.Value.Select(x => x.entyId).Distinct().ToList();
                int seq = 1;
                List<PurData> valuedatas = dic.Value.GroupBy(x => new { x.matNumber, x.taxPrice, x.taxRate, x.discountRate, x.isFree }).Select(x =>
                {
                    PurData fpur = x.FirstOrDefault();
                    fpur.qty = x.Sum(a => a.qty);
                    fpur.allAmount = x.Sum(a => a.allAmount);
                    fpur.amount = x.Sum(a => a.amount);
                    fpur.taxAmount = x.Sum(a => a.taxAmount);
                    fpur.discountAmount = x.Sum(a => a.discountAmount);
                    fpur.seq = seq++;
                    return fpur;
                }).ToList();
                try
                {
                    List<string> sqls = valuedatas.Select(x => $@"/*dialect*/ insert into RLKX_t_Cust_MXHZXX
(FID
,FSeq
,F_RLKX_WLBM  --物料编码
,F_RLKX_CGDW  --采购单位
,F_RLKX_JJDW  --计价单位
,F_RLKX_CGSL  --采购数量
,F_RLKX_JJSL  --计价数量
,F_RLKX_PRICE  --单价
,F_RLKX_HSPRICE --含税单价
,F_RLKX_JE  --金额
,F_RLKX_DISCOUNTRATE_6LR  --折扣率
,F_RLKX_DISCOUNT_8ZB  --折扣额
,F_RLKX_SL  --税率
,F_RLKX_SE  --税额
,F_RLKX_JSHJ  --价税合计
,F_RLKX_SFZP  --是否赠品
)
values(
{x.Id}
,{x.seq}
,{x.matId}
,{x.unitId}
,{x.priceUnitId}
,{x.qty}
,{x.qty}
,{x.price}
,{x.taxPrice}
,{x.amount}
,{x.discountRate}
,{x.discountAmount}
,{x.taxRate}
,{x.taxAmount}
,{x.allAmount}
,{x.isFree}
)
").ToList();
                    string sql_del = $@"delete from RLKX_t_Cust_MXHZXX where FID={firstData.Id}";
                    int i=  DBUtils.Execute(Context,sql_del);
                    i= DBUtils.ExecuteBatch(Context,sqls,500);
                  

                    //JObject Root = new JObject();
                    //Root["IsDeleteEntry"] = false;
                    //Root["IsUserModelInit"] = true;
                    //JObject Model = new JObject();
                    //Model["FID"] = firstData.Id;
                    //JArray entyArray = new JArray();
                    //foreach (int entyid in entyids)
                    //{
                    //    JObject entyObj = new JObject();
                    //    entyObj["FEntryId"] = entyid;
                    //    entyArray.Add(entyObj);
                    //}
                    //Model["FPOOrderEntry"] = entyArray;
                    //JArray collectEntyArray = new JArray();
                    //foreach (PurData purObj in valuedatas)
                    //{
                    //    JObject entyObj = new JObject();
                    //    entyObj["FEntryId"] = 0;
                    //    //物料编码
                    //    JObject F_RLKX_WLBM = new JObject();
                    //    F_RLKX_WLBM["FNumber"] = purObj.matNumber;
                    //    entyObj["F_RLKX_WLBM"] = F_RLKX_WLBM;

                    //    entyObj["F_RLKX_Price"] = purObj.price;
                    //    entyObj["F_RLKX_CGSL"] = purObj.qty;
                    //    entyObj["F_RLKX_JJSL"] = purObj.qty;
                    //    entyObj["F_RLKX_HSPrice"] = purObj.taxPrice;
                    //    entyObj["F_RLKX_JE"] = purObj.amount;
                    //    entyObj["F_RLKX_DiscountRate_6lr"] = purObj.discountRate;
                    //    entyObj["F_RLKX_Discount_8zb"] = purObj.discountAmount;
                    //    entyObj["F_RLKX_SL"] = purObj.taxRate;
                    //    entyObj["F_RLKX_SE"] = purObj.taxAmount;
                    //    entyObj["F_RLKX_JSHJ"] = purObj.allAmount;
                    //    entyObj["F_RLKX_SFZP"] = purObj.isFree==1;
                    //    collectEntyArray.Add(entyObj);
                    //}
                    //Model["F_RLKX_MXHZXX"] = collectEntyArray;
                    //Root["Model"] = Model;
                    //string json = Root.ToStringV1();
                    //string msg = string.Empty;
                    //bool res = K3HelperV1.Save(Context, "PUR_PurchaseOrder", json, ref msg);
                    //if (res)
                    //{
                    //    LogHelperV1.WSLog(Context, firstData.billNo, "采购订单汇总明细保存成功", json, true, btype);
                    //}
                    //else
                    //{
                    //    LogHelperV1.WSLog(Context, firstData.billNo, msg, json, false, btype);
                    //}

                }
                catch (Exception ex)
                {
                    LogHelperV1.WSLog(Context, firstData.billNo, "采购订单汇总明细保存异常【PUR1002】", ex.Message, false, btype);
                    continue;
                }

            }
            int maxEntyId = DBUtils.ExecuteScalar<int>(Context, $@"select MAX(FEntryID) from RLKX_t_Cust_MXHZXX", 0);
            if (maxEntyId != 0)
            {
                string sql_zz = $@"/*dialect*/ DBCC CHECKIDENT(Z_RLKX_t_Cust_MXHZXX, RESEED,{maxEntyId + 1})";
                DBUtils.Execute(Context, sql_zz);
            }

        }
//        public void MainV1(List<int> IdList)
//        {
//            List<PurData> dataList = new List<PurData>();
//            int size = 5000;
//            int icount = IdList.Count <= size ? 1 : IdList.Count % size > 0 ? IdList.Count / size + 1 : IdList.Count / size;
//            for (int i = 0; i < icount; i++)
//            {
//                List<int> ids = IdList.Skip(i * size).Take(size).ToList();
//                string sql = $@"select 
//Id=main.FID
//,billNo=main.FBILLNO
//,entyId=enty.FENTRYID
//,matNumber=mat.FNUMBER
//,price=entyF.FPRICE
//,isFree=enty.FGIVEAWAY --是否赠品
//,taxPrice=entyF.FTAXPRICE --含税单价
//,taxRate=entyF.FTAXRATE --税率
//,discountRate=entyF.FDISCOUNTRATE --折扣率
//,qty=enty.FQTY --采购数量
//,allAmount=entyF.FALLAMOUNT  --价税合计
//,amount=entyF.FAMOUNT --金额
//,taxAmount=entyF.FTAXAMOUNT --税额
//,discountAmount=entyF.FDISCOUNT --折扣额
//from t_PUR_POOrderEntry enty
//inner join T_PUR_POORDERENTRY_F entyF on enty.FENTRYID=entyF.FENTRYID
//inner join t_PUR_POOrder main on enty.FID=main.FID
//left join T_BD_MATERIAL mat on enty.FMATERIALID=mat.FMATERIALID
//where main.FID in ({string.Join(",", ids)})
//";
//                DynamicObjectCollection datas = DBUtils.ExecuteDynamicObject(Context, sql);
//                List<PurData> pList = datas.DynamicObjectCollectionToDataList<PurData>();
//                dataList.AddRange(pList);
//            }
//            if (dataList.Count < 1)
//                return;
//            var dataDic = dataList.GroupBy(x => x.billNo).ToDictionary(y => y.Key, y => y.ToList());
//            K3HelperV1.Login(Context);
//            foreach (var dic in dataDic)
//            {
//                PurData firstData = dic.Value.FirstOrDefault();
//                List<int> entyids = dic.Value.Select(x => x.entyId).Distinct().ToList();
//                List<PurData> valuedatas = dic.Value.GroupBy(x => new { x.matNumber, x.taxPrice, x.taxRate, x.discountRate, x.isFree }).Select(x =>
//                 {
//                     PurData fpur = x.FirstOrDefault();
//                     fpur.qty = x.Sum(a => a.qty);
//                     fpur.allAmount = x.Sum(a => a.allAmount);
//                     fpur.amount = x.Sum(a => a.amount);
//                     fpur.taxAmount = x.Sum(a => a.taxAmount);
//                     fpur.discountAmount = x.Sum(a => a.discountAmount);
//                     return fpur;
//                 }).ToList();
//                try
//                {
//                    JObject Root = new JObject();
//                    Root["IsDeleteEntry"] = false;
//                    Root["IsUserModelInit"] = true;
//                    JObject Model = new JObject();
//                    Model["FID"] = firstData.Id;
//                    JArray entyArray = new JArray();
//                    foreach (int entyid in entyids)
//                    {
//                        JObject entyObj = new JObject();
//                        entyObj["FEntryId"] = entyid;
//                        entyArray.Add(entyObj);
//                    }
//                    Model["FPOOrderEntry"] = entyArray;
//                    JArray collectEntyArray = new JArray();
//                    foreach (PurData purObj in valuedatas)
//                    {
//                        JObject entyObj = new JObject();
//                        entyObj["FEntryId"] = 0;
//                        //物料编码
//                        JObject F_RLKX_WLBM = new JObject();
//                        F_RLKX_WLBM["FNumber"] = purObj.matNumber;
//                        entyObj["F_RLKX_WLBM"] = F_RLKX_WLBM;

//                        entyObj["F_RLKX_Price"] = purObj.price;
//                        entyObj["F_RLKX_CGSL"] = purObj.qty;
//                        entyObj["F_RLKX_JJSL"] = purObj.qty;
//                        entyObj["F_RLKX_HSPrice"] = purObj.taxPrice;
//                        entyObj["F_RLKX_JE"] = purObj.amount;
//                        entyObj["F_RLKX_DiscountRate_6lr"] = purObj.discountRate;
//                        entyObj["F_RLKX_Discount_8zb"] = purObj.discountAmount;
//                        entyObj["F_RLKX_SL"] = purObj.taxRate;
//                        entyObj["F_RLKX_SE"] = purObj.taxAmount;
//                        entyObj["F_RLKX_JSHJ"] = purObj.allAmount;
//                        entyObj["F_RLKX_SFZP"] = purObj.isFree == 1;
//                        collectEntyArray.Add(entyObj);
//                    }
//                    Model["F_RLKX_MXHZXX"] = collectEntyArray;
//                    Root["Model"] = Model;
//                    string json = Root.ToStringV1();
//                    string msg = string.Empty;
//                    bool res = K3HelperV1.Save(Context, "PUR_PurchaseOrder", json, ref msg);
//                    if (res)
//                    {
//                        LogHelperV1.WSLog(Context, firstData.billNo, "采购订单汇总明细保存成功", json, true, btype);
//                    }
//                    else
//                    {
//                        LogHelperV1.WSLog(Context, firstData.billNo, msg, json, false, btype);
//                    }

//                }
//                catch (Exception ex)
//                {
//                    LogHelperV1.WSLog(Context, firstData.billNo, "采购订单汇总明细保存异常【PUR1002】", ex.Message, false, btype);
//                    continue;
//                }

//            }

//        }

    }
    public class PurData
    {
        public int Id { get; set; }
        public int seq { get; set; }
        public string billNo { get; set; }
        public int entyId { get; set; }
        public int unitId { get; set; }
        public int priceUnitId { get; set; }
        public int matId { get; set; }
        public string matNumber { get; set; }
        public decimal price { get; set; }
        public int isFree { get; set; }
        public decimal taxPrice { get; set; }
        public decimal taxRate { get; set; }
        public decimal discountRate { get; set; }

        public decimal qty { get; set; }
        public decimal allAmount { get; set; }
        public decimal amount { get; set; }
        public decimal taxAmount { get; set; }
        public decimal discountAmount { get; set; }

    }
}
